package com.qiu.demo.controller;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qiu.demo.entity.Article;
import com.qiu.demo.entity.ArticleCate;
import com.qiu.demo.entity.User;
import com.qiu.demo.entity.dto.ArticleDto;
import com.qiu.demo.entity.vo.ArticleCateVo;
import com.qiu.demo.entity.vo.ArticleInfoVo;
import com.qiu.demo.entity.vo.ArticleVo;
import com.qiu.demo.service.ArticleCateService;
import com.qiu.demo.service.ArticleService;
import com.qiu.demo.service.UserService;
import com.qiu.demo.util.JsonResult;
import com.qiu.demo.util.TokenUtil;

import cn.hutool.core.util.StrUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;

@RestController
@RequestMapping("/article")
@CrossOrigin
public class ArticleController {

    @Resource
    private ArticleService articleService;
    @Resource
    private ArticleCateService aticleCateService;
    @Resource
    private UserService userService;

    @Resource
    private TokenUtil tokenUtil;

    @GetMapping("list")
    public JsonResult list(Integer pagenum, Integer pagesize, String cate_id, String state,
            HttpServletRequest request) {

        Map userData = tokenUtil.parseToken(request.getHeader("Authorization"));
        String userId = userData.get("userId").toString();

        Page<Article> rowPage = new Page<>(pagenum, pagesize);
        LambdaQueryWrapper<Article> qw = new LambdaQueryWrapper<>();
        if (cate_id != null && cate_id != "") {
            qw.eq(Article::getCateId, cate_id);
        }
        if (state != null && state != "") {
            qw.eq(Article::getState, state);
        }

        qw.eq(Article::getUserId, userId);
        Page<Article> articleData = articleService.page(rowPage, qw);
        List<Article> data = articleData.getRecords();
        List<ArticleCate> cates = aticleCateService.list();
        List<ArticleVo> articleVos = data.stream()
                .map(article -> {
                    ArticleVo articleVo = new ArticleVo();
                    articleVo.setId(article.getActicleId());
                    if (article.getPubDate() != null) {
                        articleVo.setPub_date(article.getPubDate().toString());
                    } else {

                    }
                    articleVo.setState(article.getState());
                    articleVo.setTitle(article.getTitle());
                    String cateName = "";
                    for (ArticleCate cate : cates) {
                        if (cate.getCateId().toString().equals(article.getCateId())) {
                            cateName = cate.getCateName();
                            break;
                        }
                    }
                    articleVo.setCate_name(cateName);
                    return articleVo;
                })
                .collect(Collectors.toList());

        return JsonResult.success().total(articleData.getTotal()).data("data", articleVos);
    }

    @PostMapping("add")
    public JsonResult add(@RequestBody ArticleDto articleDto, HttpServletRequest request) {

        Map userData = tokenUtil.parseToken(request.getHeader("Authorization"));
        String userId = userData.get("userId").toString();

        Article article = new Article();

        article.setUserId(userId);
        article.setState(articleDto.getState());
        article.setCateId(articleDto.getCate_id());
        article.setContent(articleDto.getContent());
        article.setCoverImg(articleDto.getCover_img());
        article.setTitle(articleDto.getTitle());

        article.setPubDate(LocalDateTime.now());

        articleService.save(article);

        return JsonResult.success();
    }

    @GetMapping("info")
    public JsonResult info(String id) {

        Article article = articleService.getOne(new LambdaQueryWrapper<Article>().eq(Article::getActicleId, id));

        String cateId = article.getCateId();
        String userId = article.getUserId();

        ArticleCate articleCate = aticleCateService
                .getOne(new LambdaQueryWrapper<ArticleCate>().eq(ArticleCate::getCateId, cateId));
        User user = userService.getOne(new LambdaQueryWrapper<User>().eq(User::getUserId, userId));

        ArticleInfoVo articleInfoVo = new ArticleInfoVo();
        articleInfoVo.setId(article.getActicleId().toString());
        articleInfoVo.setTitle(article.getTitle());
        articleInfoVo.setContent(article.getContent());
        articleInfoVo.setCover_img(article.getCoverImg());
        articleInfoVo.setPub_date(article.getPubDate().toString());
        articleInfoVo.setState(article.getState());
        articleInfoVo.setCate_id(article.getCateId());
        articleInfoVo.setAuthor_id(userId);
        articleInfoVo.setCate_name(articleCate.getCateName());
        articleInfoVo.setUsername(user.getUsername());
        articleInfoVo.setNickname(user.getNickname());

        return JsonResult.success().data("info", articleInfoVo);
    }

    @PutMapping("info")
    public JsonResult info(@RequestBody ArticleDto articleDto, HttpServletRequest request) {

        Article article = new Article();
        article.setActicleId(Integer.parseInt(articleDto.getId()));
        article.setCateId(articleDto.getCate_id());
        article.setTitle(articleDto.getTitle());
        article.setContent(articleDto.getContent());
        article.setCoverImg(articleDto.getCover_img());
        article.setState(articleDto.getState());

        articleService.updateById(article);

        return JsonResult.success();
    }

    @DeleteMapping("info")
    public JsonResult del(String id) {

        articleService.removeById(id);

        return JsonResult.success();
    }
}
